#include "ARPManager.h"

using namespace arp;

// ----------------------------------------------------------------------------
// ARPManager
// ----------------------------------------------------------------------------
ARPManager::ARPManager(void *owner) : ARPObject(owner)
{
	arpCollect = NULL;
	arpCheck = NULL;
	arpAlarm = NULL;
	arpCure = NULL;
}

ARPManager::~ARPManager()
{
	close();
	if (arpCollect != NULL)
	{
		delete arpCollect;
		arpCollect = NULL;
	}
	if (arpCheck != NULL)
	{
		delete arpCheck;
		arpCheck = NULL;
	}
	if (arpAlarm != NULL)
	{
		delete arpAlarm;
		arpAlarm = NULL;
	}
	if (arpCure!= NULL)
	{
		delete arpCure;
		arpCure = NULL;
	}
}

bool ARPManager::doOpen()
{
	//
	// check NULL
	//
	if (arpCollect == NULL) goto _error;
	if (arpCheck == NULL) goto _error;
	if (arpAlarm == NULL) goto _error;
	if (arpCure == NULL) goto _error;

	//
	// set event
	//
	arpCollect->onCollect = onMyCollect;
	arpCheck->onCheck = onMyCheck;

	//
	// open
	//
	if (!arpCollect->open()) goto _error;
	if (!arpCheck->open()) goto _error;
	if (!arpAlarm->open()) goto _error;
	if (!arpCure->open()) goto _error;

	return true;
_error:
	doClose();
	return false;
}

bool ARPManager::doClose()
{
	if (arpCollect != NULL) arpCollect->close();
	if (arpCheck != NULL) arpCheck->close();
	if (arpAlarm != NULL) arpAlarm->close();
	if (arpCure != NULL) arpCure->close();
	return true;
}

void ARPManager::onMyCollect(void *owner, void *sender, Ip ip, Mac mac)
{
	ARPManager *arpManager = (ARPManager*)owner;

	arpManager->arpAlarm->alarm(ip, mac);
	arpManager->arpCheck->check(ip, mac);
}

void ARPManager::onMyCheck(void *owner, void *sender, Ip ip, Mac goodMac, Mac badMac)
{
	ARPManager *arpManager = (ARPManager*)owner;

	arpManager->arpAlarm->alarm(ip, goodMac, badMac);
	arpManager->arpCure->cure(ip, goodMac, badMac);
}

